#!/bin/bash

set -e

create_kv() {
    echo Creating kvstore machine.
    docker-machine create -d virtualbox \
        --engine-registry-mirror https://dh7glme6.mirror.aliyuncs.com \
        kvstore
    docker $(docker-machine config kvstore) run -d \
        -p "8500:8500" \
        progrium/consul --server -bootstrap-expect 1
}

create_master() {
    echo Creating cluster master
    kvip=$(docker-machine ip kvstore)

    docker-machine create -d virtualbox \
        --swarm --swarm-master \
        --swarm-discovery="consul://${kvip}:8500" \
        --engine-opt="cluster-store=consul://${kvip}:8500" \
        --engine-opt="cluster-advertise=eth1:2376" \
        --engine-registry-mirror https://dh7glme6.mirror.aliyuncs.com \
        swarm-manager
}

create_nodes(){
    kvip=$(docker-machine ip kvstore)
    echo Creating cluster nodes
    for i in 1 2; do
        docker-machine create -d virtualbox \
            --swarm \
            --swarm-discovery="consul://${kvip}:8500" \
            --engine-opt="cluster-store=consul://${kvip}:8500" \
            --engine-opt="cluster-advertise=eth1:2376" \
            --engine-registry-mirror https://dh7glme6.mirror.aliyuncs.com \
            swarm-node${i}
    done
}


teardown(){
    docker-machine rm kvstore -y
    docker-machine rm -y swarm-manager
    for i in 1 2; do
        docker-machine rm -y swarm-node${i}
    done
}

case $1 in
    up)
        create_kv
        create_master
        create_nodes
        ;;
    down)
        teardown
        ;;
    *)
        echo "Unknow command..."
        exit 1
        ;;
esac

